#!/bin/bash
# copyleft (c) 2009. lalyos

debug ()
{
	if [  "$VERBOSE" == "true" ]; then
		echo -e "$*"
	fi
}

##########################################
# checking dependecy
##########################################
which aws >/dev/null
if [ $? -ne 0 ] ; then
	echo -e "\nWARNING: you need the 'aws' script on the PATH"
	echo "you can download it from timkay.com/aws :"
	echo -e "\tcurl timkay.com/aws/aws -o aws\n"
	exit 1
fi

##########################################
# verbose/debug
##########################################
VERBOSE=false
if [ "$1" == "-v" ]; then
	VERBOSE=true
	shift
fi
if [ "$1" == "-d" ]; then
	set -x
	shift
fi

##########################################
# checking commandline parameters
##########################################
if [ $# -eq 0 ]; then 
	echo "usage: $0 [options] lis-of-ips"
	echo "    options:"
	echo "    -v: verbose output"
	echo "    -d: debug output: every internal command is echoed before execution"
	echo -e "\nexample: $0 174.129.232.73,174.129.238.127,174.129.238.180\n"
	exit 1
fi

IP_LIST=$1
debug "choosing an ip from the list: $IP_LIST"
echo $IP_LIST|sed "s/,/\n/g" > tmp_ip_list

##########################################
# getting the list of all unassigned elastic ips
##########################################
FREE_LIST=`aws dad --xml|sed -n "/publicIp/ {N;s/\n//}; /<instanceId\/>/ s/.*>\([0-9\.]\{13,15\}\)<.*/\1/p"`
echo -e "$FREE_LIST" > tmp_ip_free
debug "all free elastic ips: \n$FREE_LIST"

##########################################
# getting ips that are available and in the parameter list
##########################################
CHOOSE_FROM_LIST=`comm -12 tmp_ip_free tmp_ip_list`
echo "$CHOOSE_FROM_LIST" > tmp_choose_from
debug "free ips from the list:\n$CHOOSE_FROM_LIST"

##########################################
# counting the choices
##########################################
if [ "$CHOOSE_FROM_LIST" == "" ];then
	NUM_OF_IPS=0
else
	NUM_OF_IPS=`wc -l tmp_choose_from|sed 's/ .*//'`
fi
debug "num of ips to choose from: $NUM_OF_IPS"
if [ $NUM_OF_IPS -lt 1 ]; then
	echo -e "\nnone of the ips, from the list ($IP_LIST) are unassigned."
	exit 1
fi

##########################################
# randomly choosing from the available list
##########################################
RND=$(($RANDOM % $NUM_OF_IPS + 1))
debug "random choice is: $RND"

CHOOSEN_IP=`sed -n "$RND p" tmp_choose_from`
echo "randomly choosen ip: $CHOOSEN_IP"

##########################################
# assigning the the choosen ip to the current instance
##########################################
INSTANCE_ID=`curl -s -g http://169.254.169.254/2007-08-29/meta-data/instance-id`
debug "instance id if this machine: $INSTANCE_ID"
PUBLIC_IP=`curl -s http://169.254.169.254/2008-02-01/meta-data/public-ipv4`
debug "public ip: $PUBLIC_IP"

aws aad $CHOOSEN_IP -i $INSTANCE_ID